<template>
  <div>

    <el-row class="bread-nav">
      <ul class="bread-nav-title">
        <span>子账号管理</span>
      </ul>

      <ul class="bread-nav-content-right">
        <button class="back" @click="addSubAccountList('add', '')">新增子账号</button>
      </ul>
    </el-row>

    <div class="content">

      <table class="myTable">
        <thead>
          <tr>
            <th>
              在线
            </th>
            <th>
              子账号
            </th>
            <th>
              名称
            </th>
            <th>
              新增日期
            </th>
            <th>
              功能
            </th>
            <th>
              状态
            </th>
          </tr>
        </thead>
        <tbody v-if="list">
          <tr v-for="(item, index) in list" :key="index">
            <td>
              <span v-if="item.is_online === 0">
                  *
                </span>
              <span v-else class="isOnline">
                </span>
            </td>
            <td>
              {{item.username}}
            </td>
            <td>
              {{item.nickname}}
            </td>
            <td>
              {{CurentTime(item.created_at)}}
            </td>
            <td>
              <button class="upData" @click="addSubAccountList('edit', item)">
                修改
              </button>
              <button class="log" @click="goLog(item)">
                日志
              </button>
            </td>
            <td>
              <button @click="showpopup(item,index)" :id="'showpopup'+index">
                  <span v-if="parseInt(item.status) === 1">
                    启用
                  </span>
                <span v-if="parseInt(item.status) === 3">
                    停用
                  </span>
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <el-row class="noticeFooter">
        <ul class="noticeFooter-left">共{{pageInfo.totalCount}}笔注单 共{{pageNums.length}}页</ul>
        <ul class="noticeFooter-right">
          <button @click="GetNoticesList(1)">首页</button>
          <button @click="GetNoticesList(--currtPage)">前一页</button>
          <span>【</span>
          <button v-for="item in pageNums" :key="item" :class="item === currtPage?'noticeFooterSelected':''" @click="GetNoticesList(item)">
            {{item}}
          </button>
          <span>】</span>
          <button @click="GetNoticesList(++currtPage)">后一页</button>
          <button @click="GetNoticesList(lastPage)">末页</button>
        </ul>
      </el-row>

    </div>

    <div class="myPopup" :style="'left:'+popupX+'px;top:'+(parseInt(popupY) - parseInt(appMainTop))+'px;display:'+popupVisible">
      <table class="myTable">
        <tr>
          <th style="padding:0">
            修改帐户状态
            <button @click="popupVisible = 'none'" class="delBtn">
            </button>
          </th>
        </tr>
        <tr>
          <label>
            <input type="radio" :value="1" v-model="changeStatus.status" @change="changeSubAccStatus()">
            启用
          </label>
          <label>
            <input type="radio" :value="0" v-model="changeStatus.status" @change="changeSubAccStatus()">
            停用
          </label>

        </tr>
      </table>
    </div>

  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { user as userMap } from '@/utils/map' // 参数映射
  export default {
    name: 'subAccountList',
    data() {
      return {
        changeStatus: {
          username: '',
          status: 1,
        },
        popupX: '',
        popupY: '',
        popupVisible: 'none',

        dialogFormVisible: false, // 表单可见性
        addForm: {
          username: '',
          nickname: '',
          user_auth_key: '',
          reset_mode: 1, // 账号模式1:现金,2:信用
          menus: [],
        },
        addFormRules: {
          username: [
            {
              type: 'string',
              required: true,
              trigger: 'blur',
              message: '请输入账号',
              transform(value) {
                return value.trim()
              },
            },
            {
              min: 5,
              message: '最少包含5个字符',
              trigger: 'change',
            },
            {
              pattern: /^[a-zA-Z0-9]+$/,
              trigger: 'blur',
              message: '只能输入英文字符和数字',
            },
          ],
          nickname: [
            {
              type: 'string',
              required: true,
              trigger: 'blur',
              message: '请输入名称',
              transform(value) {
                return value.trim()
              },
            },
            {
              min: 5,
              message: '最少包含5个字符',
              trigger: 'change',
            },
            {
              pattern: /^[a-zA-Z0-9]+$/,
              trigger: 'blur',
              message: '只能输入英文字符和数字',
            },
          ],
          user_auth_key: [
            {
              type: 'string',
              required: true,
              trigger: 'blur',
              message: '请输入密码',
            },
            {
              min: 6,
              message: '最少包含6个字符',
              trigger: 'change',
            },
            {
              pattern: /^[a-zA-Z0-9]+$/,
              trigger: 'blur',
              message: '只能输入英文字符和数字',
            },
          ],
          menus: [
            {
              required: true,
              trigger: 'change',
              message: '请选择权限',
            },
          ],
        },
        // 查詢參數
        params: {
          perpage: 5, // 每页数量
        },
        // 分页信息
        pageInfo: '',
        list: null,
        loading: false,
        userMap: userMap,
        lastPage: 1, // 最后一页
        currtPage: 1, // 当前页
      }
    },
    filters: {},
    computed: {
      ...mapGetters(['info', 'appMainTop']),
      pageNums() {
        const num = Math.ceil(parseInt(this.pageInfo.totalCount) / parseInt(this.pageInfo.pageSize))
        this.lastPage = num
        const ArrayNum = []
        for (let i = 1; i <= num; i++) {
          ArrayNum.push(i)
        }
        return ArrayNum
      },
    },
    created() {
      // 拉取数据
      this.fetchData()
    },
    methods: {
      showpopup(item, index) {
        this.changeStatus.status = item.status
        this.changeStatus.username = item.username
        this.popupVisible = 'block'
        const el = document.getElementById('showpopup' + index)
        this.popupX = el.getBoundingClientRect().left - 100
        this.popupY = el.getBoundingClientRect().top + 25
        setTimeout(() => {
          this.popupVisible = 'none'
        }, 5000)
      },

      goLog(item) {
        this.$router.push({
          name: `profile_loginlog`,
          query: {
            userName: item.username,
          },
        })
      },
      changeSubAccStatus() {
        const params = {
          subAcc: this.changeStatus.username,
          status: this.changeStatus.status,
        }
        this.$store.dispatch('ChangeSubaccStatus', params)
          .then(response => {
            this.$message({
              type: 'success',
              message: response.message,
            })
            this.fetchData()
          })
        this.popupVisible = 'none'
      },
      addSubAccountList(value, info) {
        this.$router.push({
          name: `user_addSubAccountList`,
          query: {
            type: value,
            userInfo: info,
          },
        })
      },
      GetNoticesList(value) {
        if (value < 0) {
          value = 1
        }
        if (value > this.lastPage) {
          value = this.lastPage
        }
        this.$store.dispatch('ListSubAccount', value)
          .then(response => {
            if (response.data === undefined) {
              this.$message({
                type: 'success',
                message: response.message,
              })
            } else {
              if (response.data.length > 0) {
                this.list = response.data
              }
              this.pageInfo = response.pageinfo
              this.currtPage = value
            }
          })
      },
      CurentTime(value) {
        const now = new Date(value * 1000)
        const year = now.getFullYear() // 年
        const month = now.getMonth() + 1 // 月
        const day = now.getDate() // 日
        let clock = year + '-'
        if (month < 10) {
          clock += '0'
        }
        clock += month + '-'
        if (day < 10) {
          clock += '0'
        }
        clock += day
        return (clock)
      },
      // 获取数据
      fetchData() {
        this.loading = true
        this.$store
          .dispatch('ListSubAccount', 1)
          .then(response => {
            this.loading = false
            console.log('++++++++++++', response)
            // const res = response.list
            // 遍历格式化数据
            // this.list = res.map(row => {
            //   this.$set(row, 'edit', false) // 需要绑定的属性要先声明
            //   this.$set(row, 'delete', false) // 需要绑定的属性要先声明
            //   row.menus = row.menus.split(',') // 转化成arr
            //
            //   row.initNickname = row.nickname //  不用绑定的属性
            //   row.initMenus = row.menus //  不用绑定的属性
            //   row.initStatus = row.status //  不用绑定的属性
            //   row.user_auth_key = '' //  不用绑定的属性
            //
            //   return row
            // })
            if (response.data.length > 0) {
              this.list = response.data
            }
            console.log(response.pagination)
            this.pageInfo = response.pageinfo
            this.currtPage = 1
          })
      },
      checkChange(...args) {
        // console.log(args);
      },
      // 添加确认
      confirmAdd() {
        // 验证数据
        this.$refs.addForm.validate(valid => {
          if (valid) {
            this.loading = true
            // 新增子账号
            this.$store
              .dispatch('ValidateAddSubAccount', { SubAccountForm: this.addForm })
              .then(response => {
                this.loading = false
                this.errorMsg = ''
                console.log('response.length === 0', response.status)
                if (response.status) {
                  this.loading = true
                  // 服务端验证通过
                  this.$store
                    .dispatch('AddSubAccount', { SubAccountForm: this.addForm })
                    .then(res => {
                      this.loading = false
                      console.log('************', res)
                      if (parseInt(res)) {
                        // 添加成功,返回id
                        this.dialogFormVisible = false // 隐藏dialog
                        this.$message({
                          message: '新增成功!',
                          type: 'success',
                        })
                        //
                        this.fetchData()
                      } else {
                        this.$message({
                          message: Object.values(res)[0].toString(),
                          type: 'error',
                        })
                      }
                    })
                    .catch(error => {
                      console.log(error)
                      this.loading = false
                    })
                } else {
                  // 验证失败
                  this.$message({
                    message: Object.values(response)[0].toString(),
                    type: 'error',
                  })
                  console.log('服务器端验证失败')
                }
              })
              .catch(error => {
                console.log(error)
                this.loading = false
              })
          } else {
            return false
          }
        })
      },
      // 取消添加
      cancelAdd() {
        this.dialogFormVisible = false
        this.$refs.addForm.resetFields()
      },

      // 取消修改
      cancelEdit(row) {
        row.edit = false
        row.nickname = row.initNickname
        row.menus = row.initMenus
        row.status = row.initStatus
        row.user_auth_key = ''
      },

      // 更新子账号
      confirmEdit(row) {
        // 验证数据
        if (row.username.trim().length <= 0) {
          this.$message({
            message: '请填写账号',
            type: 'error',
          })
          return
        } else if (row.nickname.trim().length <= 0) {
          this.$message({
            message: '请填写名称',
            type: 'error',
          })
          return
        }
        if (row.user_auth_key.trim().length <= 0) {
          row.user_auth_key = ''
        }

        this.loading = true
        // 修改
        this.$store
          .dispatch('ValidateUpdateSubAccount', { SubAccountUpdateForm: row })
          .then(response => {
            this.loading = false
            this.errorMsg = ''
            if (response.length === 0) {
              this.loading = true
              // 服务端验证通过
              this.$store
                .dispatch('UpdateSubAccount', { SubAccountUpdateForm: row })
                .then(res => {
                  this.loading = false
                  if (res === true) {
                    // 编辑成功
                    row.edit = false // 隐藏编辑栏
                    this.$message({
                      message: '修改成功!',
                      type: 'success',
                    })
                    this.fetchData()
                  } else {
                    this.$message({
                      message: Object.values(res)[0].toString(),
                      type: 'error',
                    })
                  }
                })
                .catch(error => {
                  console.log(error)
                  this.loading = false
                })
            } else {
              // 验证失败
              this.$message({
                message: Object.values(response)[0].toString(),
                type: 'error',
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.loading = false
          })
      },

      // 确认删除
      confirmDelete(row) {
        row.delete = false
        this.$store
          .dispatch('DeleteSubAccount', { username: row.username })
          .then(response => {
            this.loading = false
            // console.log(response);
            if (response === true) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.fetchData()
            } else {
              // 验证失败
              this.$message({
                message: Object.values(response)[0].toString(),
                type: 'error',
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.loading = false
          })
      },

      // 当前页变化
      handleCurrentChange(value) {
        this.pagination.currentPage = value
        this.fetchData()
      },

      // 每页显示数量变化
      handlePageSizeChange(value) {
        this.params.perpage = value
        this.fetchData()
      },
    },
    watch: {
      $route(to, from) {
        // 监控路由变化,从新加载数据
        if (to.params !== from.params) {
          console.log(to.params)
        }
      },
    },
  }
</script>

<style scoped>

  .content{
    padding: 10px;
  }
  .myTable{
    width: 100%;
    border-collapse: collapse;
    border-spacing: 0;
    margin: 2px  0;
  }
  .myTable th{
    background: url(/static/agent/img/table_head.gif) repeat-x;
    height: 25px;
    text-align: center;
    color: #131950;
    font-weight: bold;
    line-height: 25px;
    font-size:14px;
    padding-left: 10px;
    padding-right: 10px;
    border: 1px solid #B9C2CB;
    margin: 0;
  }
  .myTable td{
    text-align: center;
    color: #131950;
    line-height: 25px;
    font-size:14px;
    padding: 5px;
    border: 1px solid #B9C2CB;
    box-sizing: border-box;
  }
  .deepColor{
    background-color: #F2F2F2;
  }
  .tableBtn{
    color:blue;
    background-color: rgba(0,0,0,0);
    border: none;
    outline: none;
    cursor: pointer;
  }
  .tableBtn:hover{
    text-decoration: underline;
  }
  .isOnline{
    background: url(/static/agent/img/u1.gif) no-repeat;
    width: 20px;
    height: 20px;
    display: inline-block;
  }
  .upData{
    background: url(/static/agent/img/edit.gif) no-repeat left center;
    padding-left: 14px;
    text-decoration: none;
    cursor: pointer;
    color: #3e34fc;
    border:none;
  }
  .upData:hover{
    text-decoration: underline;
    color:red
  }
  .log{
    background: url(/static/agent/img/22.gif) no-repeat left center;
    padding-left: 14px;
    text-decoration: none;
    cursor: pointer;
    color: #3e34fc;
    border:none;
  }
  .log:hover{
    text-decoration: underline;
    color:red
  }
  .bread-nav {
    height: 30px;
    font-size: 13px;
    line-height: 30px;
    background: #ECEFF2;
    border-bottom: 1px solid #d0dff2;
    padding: 0 0 0 10px;
    overflow: hidden;
  }

  .bread-nav-title {
    color: #386399;
    font-weight: bold;
    float: left;
    background: url("../../../../static/agent/img/tb.png") no-repeat left center;
    padding-left: 20px;
  }

  .bread-nav-content-right {
    float: right;
  }

  .bread-nav-content-right .back {
    border: 0;
    color: #386399;
    display: inline-block;
    font-weight: bold;
    margin-right: 10px;
    background-color: rgba(0,0,0,0);
  }

  .bread-nav-content-right .back:hover {
    text-decoration: underline;
  }

  .noticeFooter {
    background-color: #EEEEEE;
    margin: 5px 0;
    font-size:13px;
    padding:5px 0;
  }

  .noticeFooter-left {
    float: left;
  }

  .noticeFooter-right {
    float: right;
  }

  .noticeFooter-right button {
    border: 0;
    background-color: rgba(0, 0, 0, 0);
    color: blue;
    cursor: pointer;
  }

  .noticeFooter-right button:hover {
    color: red;
    text-decoration: underline;
  }

  .noticeFooterSelected {
    color: #ccc !important;
  }



  .myPopup{
    position: absolute;
    z-index:2100;
    background-color: #FFF;
    width:130px;
    text-align: center;
  }
  .delBtn{
    border:0;
    background: url(/static/agent/img/del.gif) no-repeat;
    width: 16px;
    height: 16px;
    float: right;
    cursor: pointer;
    vertical-align: middle;
    margin: 4px 2px 0 0;
  }
</style>
